import React, { CSSProperties, useEffect, useState } from 'react';
import styled from 'styled-components';
import { confirm } from '@tauri-apps/plugin-dialog';
import { PlusOutlined } from '@ant-design/icons';
import { Button, Card, Drawer, Space, Table } from "antd";

import { Application, APPLICATION_PUBLIC_LABELS, ApplicationCategory, ApplicatonPublicStatus, appstoreApplicationCommit, appstoreApplicationUncommit, appstoreAuditApplication, appstoreGetCategories, appstoreGetMyApplication } from '@/services';
import { MyApplicationDetail, MyApplicationView } from './my-application-detail';
import { ApplicationUploader } from './application-uploader';
import { ApplicationUploadVersion } from './application-upload-version';
import { MyApplicationEditor } from './my-application-editor';
import { openApplication } from '@/components';

export interface MyApplicationsTableProps {
    style?: CSSProperties;
}

export const MyApplicationsTable: React.FC<MyApplicationsTableProps> = (props) => {

    const [loading, setLoading] = useState<boolean>(false);

    const [versionOpen, setVersionOpen] = useState<boolean>(false);

    const [editOpen, setEditOpen] = useState<boolean>(false);

    const [categories, setCategories] = useState<Array<ApplicationCategory>>([]);

    const [detailOpen, setDetailOpen] = useState<boolean>(false);

    const [dataOpen, setDataOpen] = useState<boolean>(false);

    const [uploadOpen, setUploadOpen] = useState<boolean>(false);

    const [uploadVersionOpen, setUploadVersionOpen] = useState<boolean>(false);

    const [sharedObjects, setSharedObjects] = useState<Array<Application>>([]);

    const [selected, setSelected] = useState<Application | null>(null);

    const [page, setPage] = useState<number>(1);

    const [pageSize, setPageSize] = useState<number>(10);

    const [total, setTotal] = useState<number>(0);

    useEffect(() => {
        // appstoreGetCategories
        appstoreGetCategories().then((data) => {
            setCategories(data);
        });
    }, []);

    const columns = [
        {
            title: '标识',
            dataIndex: 'identifier',
            key: 'identifier',
            width: '140px',
            ellipsis: true,
        },
        {
            title: '名称',
            dataIndex: 'name',
            key: 'name',
            width: '220px',
            ellipsis: true,
        },
        {
            title: '审核状态',
            dataIndex: 'publicStatus',
            key: 'publicStatus',
            width: '120px',
            ellipsis: true,
            render: (text, record, index) => {
                let label = APPLICATION_PUBLIC_LABELS[record.publicStatus];
                if (label) {
                    return label;
                } else {
                    return '未知状态';
                }
            }
        },
        {
            title: '操作',
            dataIndex: '操作',
            key: '操作',
            render: (_, record, index) => {

                let runButton = '';

                let editButton = <Button
                    type={'link'}
                    size={'small'}
                    onClick={async () => {
                        setSelected(record);
                        setEditOpen(true);
                    }}
                >编辑</Button>;

                if (record.publicStatus === ApplicatonPublicStatus.PUBLIC) {
                    //已经上线
                    return (
                        <Space size="middle" key={record.identifier + index}>
                            {runButton}
                            {editButton}
                            <Button
                                type={'link'}
                                size={'small'}
                                onClick={async () => {
                                    setSelected(record);
                                    setUploadVersionOpen(true);
                                }}
                            >上传版本</Button>
                        </Space>
                    );
                } else if (record.publicStatus === ApplicatonPublicStatus.INIT || record.publicStatus === ApplicatonPublicStatus.CANNEL || record.publicStatus === ApplicatonPublicStatus.FAIL) {
                    //审核失败
                    return (
                        <Space size="middle" key={record.identifier + index}>
                            {runButton}
                            {editButton}
                            <Button
                                type={'link'}
                                size={'small'}
                                onClick={async () => {
                                    //提示
                                    const confirmed2 = await confirm('确定要提交审核？', { title: '提交审核', kind: 'warning' });
                                    if (confirmed2) {
                                        let res = await appstoreApplicationCommit(record.identifier);
                                        await request(page, pageSize);
                                    }
                                }}
                            >提交审核</Button>
                        </Space>
                    );
                } else if (record.publicStatus === ApplicatonPublicStatus.AUDITING) {
                    //审核中
                    return (
                        <Space size="middle" key={record.identifier + index}>
                            {runButton}
                            <Button
                                type={'link'}
                                size={'small'}
                                onClick={async () => {
                                    //提示
                                    const confirmed2 = await confirm('确定要撤销审核？', { title: '撤销审核', kind: 'warning' });
                                    if (confirmed2) {
                                        let res = await appstoreApplicationUncommit(record.identifier);
                                        await request(page, pageSize);
                                    }
                                }}
                            >撤销审核</Button>
                        </Space>
                    );
                }
                return (
                    <Space size="middle" key={record.identifier + index}>
                        {runButton}
                        <Button
                            type={'link'}
                            size={'small'}
                            onClick={async () => {
                                setSelected(record);
                                setDetailOpen(true);
                            }}
                        >查看</Button>
                    </Space>
                );
            }
        },
    ];

    const request = async (page: number, pageSize: number) => {
        setLoading(true);
        const { total, data } = await appstoreGetMyApplication(page, pageSize);
        console.log(data);
        setSharedObjects(data);
        setTotal(total);
        setLoading(false);
    };

    useEffect(() => {
        request(page, pageSize);
    }, [page, pageSize]);

    return (
        <Container>
            <StyledCard title={'我的应用'}>
                <Buttons>
                    <Button style={{ width: '90px' }} loading={loading} type={'primary'} icon={<PlusOutlined />}
                        onClick={async () => {
                            setSelected(null);
                            setUploadOpen(true);
                        }}
                    >添加</Button>
                </Buttons>
                <Table
                    bordered
                    loading={loading}
                    rowKey={'identifier'}
                    pagination={{
                        showSizeChanger: true,
                        total: total,
                        current: page,
                        pageSize: pageSize,
                        onChange: (page, pageSize) => {
                            setPage(page);
                        },
                        onShowSizeChange: (current, size) => {
                            setPageSize(size);
                        }
                    }}
                    dataSource={sharedObjects} columns={columns} />
            </StyledCard>
            <Drawer
                title="数据统计"
                onClose={() => {
                    setDataOpen(false);
                }}
                width={'calc(100% - 220px)'}
                destroyOnClose={true}
                open={dataOpen}>
            </Drawer>
            <Drawer
                title="应用详情"
                onClose={() => {
                    setDetailOpen(false);
                }}
                width={'calc(100% - 220px)'}
                destroyOnClose={true}
                open={detailOpen}>
                <MyApplicationView categories={categories} item={selected}></MyApplicationView>
            </Drawer>
            <Drawer
                title="添加应用"
                onClose={() => {
                    setUploadOpen(false);
                }}
                width={'calc(100% - 220px)'}
                destroyOnClose={true}
                open={uploadOpen}>
                <ApplicationUploader categories={categories} onFinish={async () => {
                    //刷新列表
                    await request(page, pageSize);
                    setUploadOpen(false);
                }}></ApplicationUploader>
            </Drawer>
            <Drawer
                title="上传版本"
                onClose={() => {
                    setUploadVersionOpen(false);
                }}
                width={'calc(100% - 220px)'}
                destroyOnClose={true}
                open={uploadVersionOpen}>
                <ApplicationUploadVersion item={selected}></ApplicationUploadVersion>
            </Drawer>
            <Drawer
                title="编辑"
                onClose={() => {
                    setEditOpen(false);
                }}
                width={'calc(100% - 270px)'}
                destroyOnClose={true}
                open={editOpen}>
                <MyApplicationEditor categories={categories} item={selected} onFinish={async () => {
                    await request(page, pageSize);
                    setEditOpen(false);
                }}></MyApplicationEditor>
            </Drawer>
        </Container>
    );
}


const Container = styled.div`
    width: 100%;
    height: 100%;
    padding:20px;
    padding-top:30px;
`;

const StyledCard = styled(Card)`
    width: 100%;
    height: 100%;
`;

const Buttons = styled.div`
    width: 100%;
    display: flex;
    justify-content: flex-end;
    padding: 6px 6px;
    gap:10px;
`;
